package com.lightkits.wms.domain.pickreport;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lightkits.common.CommonToolsUtil;
import com.lightkits.common.MessageUtil;
import com.lightkits.common.db.entity.FndResourceTl;
import com.lightkits.common.model.SysCodeValueDTO;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsCommonMapper;
import com.lightkits.wms.database.model.PickReportModel;
import com.lightkits.wms.dto.pickreport.QueryPickReportsRequestType;
import com.lightkits.wms.dto.pickreport.QueryPickReportsResponseType;
import com.lightkits.wms.dto.pickreport.models.PickReportDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * QueryPickReportsExecutor
 *
 * @author zhuangwei.zheng@hand-china.com
 * Created on 2019/5/8 11:23
 */
@Component
public class QueryPickReportsExecutor implements ServiceExecutor<QueryPickReportsRequestType, QueryPickReportsResponseType> {
    private final WmsCommonMapper wmsCommonMapper;

    @Autowired
    public QueryPickReportsExecutor(WmsCommonMapper wmsCommonMapper) {
        this.wmsCommonMapper = wmsCommonMapper;
    }

    @Override
    public QueryPickReportsResponseType service(QueryPickReportsRequestType request) {
        QueryPickReportsResponseType response = new QueryPickReportsResponseType();
        response.setSuccessful(true);
        try {
            Long creationDateFrom = ParseUtil.tryLongOptional(request.getCreationDateFrom());
            Long creationDateTo = ParseUtil.tryLongOptional(request.getCreationDateTo());
            Date creationDateFromD = null;
            if (creationDateFrom != null) {
                creationDateFromD = new Date(creationDateFrom);
            }
            Date creationDateToD = null;
            if (creationDateTo != null) {
                creationDateToD = new Date(creationDateTo);
            }
            boolean usePage = true;
            if (request.getCurrentPage() <= 0 || request.getPageSize() <= 0) {
                usePage = false;
            }
            Page page = null;
            if (usePage) {
                page = PageHelper.startPage(request.getCurrentPage(), request.getPageSize());
            }
            List<PickReportModel> models = wmsCommonMapper.queryWmRequestByPara(
                    request.getProcessStatus(),
                    request.getWmRequestNum(),
                    request.getProductionLineId(),
                    request.getMoId(),
                    request.getItemId(),
                    request.getCreatorId(),
                    creationDateFromD,
                    creationDateToD,
                    request.getOrgId(),
                    request.getTypes()
            );
            List<String> resourceIds = new ArrayList<>();
            models.forEach(target -> {
                resourceIds.add(target.getProdLineId());
                resourceIds.add(target.getCreatorId());
            });
            List<FndResourceTl> resourceTls = new ArrayList<>();
            if (!resourceIds.isEmpty()) {
                List<FndResourceTl> resList = new FndResourceTl()
                        .selectList(new EntityWrapper<FndResourceTl>()
                                .in(FndResourceTl.RESOURCE_ID, resourceIds));
                resourceTls.addAll(resList);
            }
            List<SysCodeValueDTO> codeValueDTOS = MessageUtil.querySysCodeValue("WM_REQUEST_TYPE");
            List<PickReportDTO> dtoList = models
                    .stream()
                    .map(model -> new PickReportDTO() {
                        {
                            setCreationDate(ObjectUtil.toString(model.getCreationDate().getTime()));
                            setMoNumber(model.getMoNumber());
                            setOrgName(model.getOrgName());
                            setWmRequestId(model.getWmRequestId());
                            setWmRequestNum(model.getWmRequestNum());
                            Optional<FndResourceTl> workerOpt = resourceTls
                                    .stream()
                                    .filter(target -> Objects.equals(target.getResourceId().toString(), model.getCreatorId()))
                                    .findFirst();
                            workerOpt.ifPresent(target -> setCreatorName(target.getResourceName()));
                            Optional<FndResourceTl> prodLineOpt = resourceTls
                                    .stream()
                                    .filter(target -> Objects.equals(target.getResourceId().toString(), model.getProdLineId()))
                                    .findFirst();
                            prodLineOpt.ifPresent(target -> setProdLineName(target.getResourceName()));
                            Optional<SysCodeValueDTO> codeValueDTO = codeValueDTOS
                                    .stream()
                                    .filter(target -> Objects.equals(target.getCoedValue(), model.getTypeValue()))
                                    .findFirst();
                            codeValueDTO.ifPresent(target -> setTypeMeaning(target.getCodeMeaning()));
                        }
                    }).collect(Collectors.toList());
            response.setReportDTOList(dtoList);
            if (page != null) {
                response.setTotal(new Long(page.getTotal()).intValue());
            } else {
                response.setTotal(dtoList.size());
            }
        } catch (Exception e) {
            CommonToolsUtil.executeException(e, response);
        }
        return response;
    }
}
